<template>
  <view class="forget-page">
    <view class="content">
      <!-- 邮箱输入 -->
      <view class="form-label">请填写邮箱</view>
      <view class="input-group">
        <view class="input-container">
          <input 
            v-model="formData.username" 
            class="input-field" 
            placeholder="请填写邮箱地址" 
          />
        </view>
      </view>

      <!-- 验证码输入 -->
      <view class="form-label">验证码</view>
      <view class="input-group">
        <view class="input-container">
          <input 
            v-model="formData.captcha" 
            class="input-field" 
            placeholder="请填写邮箱验证码" 
            maxlength="6"
          />
          <view 
            class="get-code-btn" 
            :class="{ disabled: codeGetDisable || countdown > 0 }"
            @click="onGetVerifyCode"
          >
            <text class="get-code-text">{{ countdown > 0 ? `${countdown}s后重发` : '获取验证码' }}</text>
          </view>
        </view>
      </view>

      <!-- 密码输入 -->
      <view class="form-label">密码</view>
      <view class="input-group">
        <view class="input-container">
          <input 
            v-model="formData.password" 
            class="input-field" 
            placeholder="请填写密码,至少8位包括数字和大小写字母" 
            :password="true"
          />
        </view>
      </view>

      <!-- 确认密码输入 -->
      <view class="form-label">确认密码</view>
      <view class="input-group">
        <view class="input-container">
          <input 
            v-model="formData.password2" 
            class="input-field" 
            placeholder="请再次填写密码" 
            :password="true"
          />
        </view>
      </view>

      <!-- 提交按钮 -->
      <view class="submit-btn" :class="{ disabled: loading }" @click="onSubmit">
        <text class="submit-text">{{ loading ? '提交中...' : '提交' }}</text>
      </view>
    </view>
  </view>
</template>

<script>
import { getEmailCaptcha, forgetPassword } from '@/api/auth'
import { checkCaptchaThrottle } from '@/utils/captcha-throttle'

export default {
  name: 'ForgetPassword',
  data() {
    return {
      formData: {
        username: '',
        captcha: '',
        password: '',
        password2: ''
      },
      loading: false,
      codeGetDisable: false,
      countdown: 0,
      timer: null,
      lastClickTime: 0 // 上次点击时间，用于防抖
    }
  },
  
  beforeDestroy() {
    // 清理定时器
    if (this.timer) {
      clearInterval(this.timer)
    }
  },
  
  methods: {
    // 获取邮箱验证码
    onGetVerifyCode() {
      // 判断是否可以发送
      if (this.codeGetDisable || this.countdown > 0) {
        return
      }

      // 验证邮箱
      if (!this.formData.username) {
        uni.showToast({
          title: '请填写邮箱地址',
          icon: 'none'
        })
        return
      }

      // 验证邮箱格式
      const emailReg = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/
      if (!emailReg.test(this.formData.username)) {
        uni.showToast({
          title: '请输入正确的邮箱地址',
          icon: 'none'
        })
        return
      }

      // 防抖检查：1秒内最多4个请求
      const throttleCheck = checkCaptchaThrottle()
      if (!throttleCheck.canSend) {
        uni.showToast({
          title: throttleCheck.message,
          icon: 'none'
        })
        return
      }

      // 调用发送邮箱验证码接口
      getEmailCaptcha(this.formData.username)
        .then(response => {
          if (response.code === 200) {
            uni.showToast({
              title: '验证码已发送',
              icon: 'none'
            })
            // 开始倒计时
            this.startCountdown()
          } else {
            uni.showToast({
              title: response.message || '发送失败',
              icon: 'none'
            })
          }
        })
        .catch(error => {
          uni.showToast({
            title: error.message || '发送失败',
            icon: 'none'
          })
        })
    },

    // 开始倒计时
    startCountdown() {
      this.countdown = 60
      this.codeGetDisable = true
      this.timer = setInterval(() => {
        this.countdown--
        if (this.countdown <= 0) {
          clearInterval(this.timer)
          this.timer = null
          this.codeGetDisable = false
        }
      }, 1000)
    },

    // 提交表单
    onSubmit() {
      if (this.loading) {
        return
      }

      // 防抖检查：500ms内不允许重复点击
      const now = Date.now()
      if (now - this.lastClickTime < 500) {
        return
      }
      this.lastClickTime = now

      // 验证邮箱
      if (!this.formData.username) {
        uni.showToast({
          title: '请填写邮箱地址',
          icon: 'none'
        })
        return
      }

      // 验证邮箱格式
      const emailReg = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/
      if (!emailReg.test(this.formData.username)) {
        uni.showToast({
          title: '请输入正确的邮箱地址',
          icon: 'none'
        })
        return
      }

      // 验证验证码
      if (!this.formData.captcha) {
        uni.showToast({
          title: '请填写验证码',
          icon: 'none'
        })
        return
      }

      // 验证密码
      if (!this.formData.password) {
        uni.showToast({
          title: '请填写密码',
          icon: 'none'
        })
        return
      }

      // 验证密码格式（8-20位，包含数字和大小写字母）
      const passwordReg = /^[a-zA-Z0-9!@#$%^&*]{8,20}$/
      if (!passwordReg.test(this.formData.password)) {
        uni.showToast({
          title: '密码至少8位，包括数字和大小写字母',
          icon: 'none'
        })
        return
      }

      // 验证两次密码是否一致
      if (this.formData.password !== this.formData.password2) {
        uni.showToast({
          title: '两次密码输入不一致',
          icon: 'none'
        })
        return
      }
 
      this.loading = true

      // 调用忘记密码接口
      forgetPassword({
        username: this.formData.username,
        password: this.formData.password,
        captcha: this.formData.captcha,
        loginType: 1 // 1: 邮箱
      }).then(response => {
        this.loading = false
        if (response.code === 200) {
          uni.showToast({
            title: '密码重置成功',
            icon: 'none'
          })
          setTimeout(() => {
            uni.navigateTo({ url: '/subPages/auth/login' })
          }, 1500)
        } else {
          uni.showToast({
            title: response.message || '重置密码失败',
            icon: 'none'
          })
        }
      }).catch(e => {
        this.loading = false
        uni.showToast({
          title: e.message || '重置密码失败',
          icon: 'none'
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.forget-page {
  min-height: 100vh;
  background: #f5f5f5;
}

.content {
  padding: 40rpx 60rpx;
}

.form-label {
  font-size: 28rpx;
  font-weight: 500;
  color: #333;
  margin-bottom: 16rpx;
  margin-top: 32rpx;

  &:first-child {
    margin-top: 0;
  }
}

.input-group {
  margin-bottom: 8rpx;

  .input-container {
    position: relative;
    display: flex;
    align-items: center;
    height: 100rpx;
    padding: 0 30rpx;
    background-color: #fff;
    border: 2rpx solid #e4e7ed;
    border-radius: 16rpx;
    transition: all 0.3s ease;

    &:focus-within {
      border-color: #00d4aa;
      box-shadow: 0 0 0 2rpx rgba(0, 212, 170, 0.1);
    }

    .input-field {
      flex: 1;
      height: 100%;
      font-size: 32rpx;
      color: #333;
      background: transparent;
      border: none;

      &::placeholder {
        font-size: 28rpx;
        color: #c0c4cc;
      }
    }

    .get-code-btn {
      display: flex;
      align-items: center;
      justify-content: center;
      min-width: 180rpx;
      height: 60rpx;
      padding: 0 20rpx;
      margin-left: 20rpx;
      cursor: pointer;
      transition: all 0.3s ease;

      &:active {
        opacity: 0.7;
      }

      &.disabled {
        cursor: not-allowed;
      }

      .get-code-text {
        font-size: 26rpx;
        font-weight: 500;
        color: #00c299;
        white-space: nowrap;
      }

      &.disabled .get-code-text {
        color: #999;
      }
    }
  }
}

.submit-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 96rpx;
  margin-top: 60rpx;
  background: #00d4aa;
  border-radius: 48rpx;
  cursor: pointer;
  transition: all 0.25s ease;

  &:active:not(.disabled) {
    transform: scale(0.98);
    opacity: 0.85;
  }

  &.disabled {
    background: #f0f0f0;
    cursor: not-allowed;
    
    .submit-text {
      color: #aaa;
    }
  }

  .submit-text {
    font-size: 34rpx;
    font-weight: 500;
    color: #fff;
  }
}
</style>
